package com.hzqy.service.zxbh.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class HttpUtil {
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	private static final String CHARSET = "UTF-8";
	public static final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public static Map<String, String> sendPost(String url,Map<String, String> paramsdata,Map<String,String> heards) {
		Map<String, String> result = new HashMap<String, String>();
		// 参数
		URI uri =null;
		try {
			URIBuilder ub = new URIBuilder(url);
			List<NameValuePair> params = new ArrayList<>();
			for (Map.Entry<String, String> entry : paramsdata.entrySet()) {
				String key = entry.getKey();
				String value = entry.getValue();
				NameValuePair nameValuePair = new BasicNameValuePair(key, value);
				params.add(nameValuePair);
			}
			ub.setParameters(params);
			uri=ub.build();
		} catch (URISyntaxException e1) {
			e1.printStackTrace();
		}
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		// 创建Post请求
		HttpPost httpPost = new HttpPost(uri);
		// 我这里利用阿里的fastjson，将Object转换为json字符串;
		// (需要导入com.alibaba.fastjson.JSON包)
		StringEntity entity = new StringEntity(JSON.toJSONString(new Object()), "UTF-8");
		// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
		httpPost.setEntity(entity);
		httpPost.setHeader("Source","InterNetSend");
		httpPost.setHeader("Content-Type", "application/json;charset=utf8");
		for(Map.Entry<String, String> entry : heards.entrySet()){
			String mapKey = entry.getKey();
			String mapValue = entry.getValue();
			httpPost.setHeader(mapKey, mapValue);
		}
		//httpPost.setHeader("Connection", "Keep-Alive");
		//httpPost.setHeader("Charset", CHARSET);
		//httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
			//System.out.println("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				//System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				//System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
				result.put("msg", EntityUtils.toString(responseEntity));
				//EntityUtils.toString(responseEntity, "UTF-8");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		result.put("success", "ok");
		return result;
	}
	public static Map<String, String> get(String urlStr,Map<String,String> heards) {
		PrintWriter writer = null;
		HttpURLConnection httpConn = null;
		Map<String, String> result = new HashMap<String, String>();
		String msg = "";
		String success = "0";
		
		
		try {// 获取HttpURLConnection连接对象
			URL url = new URL(urlStr);
			httpConn = (HttpURLConnection) url.openConnection();
			// 设置连接属性
			httpConn.setConnectTimeout(20000);
			httpConn.setReadTimeout(30000);
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setUseCaches(false);
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Charset", CHARSET);
			httpConn.setRequestProperty("Content-Type", "text/html");
			httpConn.setRequestMethod("GET");
			for(Map.Entry<String, String> entry : heards.entrySet()){
				String mapKey = entry.getKey();
				String mapValue = entry.getValue();
				httpConn.setRequestProperty(mapKey, mapValue);
			}
			
			int respCode = httpConn.getResponseCode();
			if (respCode == 200) {
				success = "1";
				msg = getStringFromInputStream(httpConn.getInputStream());
			}else{
				success = "2";
				msg = "response_status: " + respCode;
			}
		} catch (Exception e) {
			success = "2";
			//msg = e.getMessage();
		}finally {
			if(httpConn != null)
				httpConn.disconnect();
			close(writer);
		}
		
		
		result.put("msg", msg);
		result.put("success", success);
		return result;
	}
	
	public static Map<String, String> post(String urlStr, String text,Map<String,String> heards) {
		PrintWriter writer = null;
		HttpURLConnection httpConn = null;
		Map<String, String> result = new HashMap<String, String>();
		String msg = "";
		String success = "0";
		
		
		try {// 获取HttpURLConnection连接对象
			URL url = new URL(urlStr);
			httpConn = (HttpURLConnection) url.openConnection();
			// 设置连接属性
			httpConn.setConnectTimeout(20000);
			httpConn.setReadTimeout(30000);
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setUseCaches(false);
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Charset", CHARSET);
			//httpConn.setRequestProperty("Content-Type", "application/json");
			httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			httpConn.setRequestMethod("POST");
			for(Map.Entry<String, String> entry : heards.entrySet()){
				String mapKey = entry.getKey();
				String mapValue = entry.getValue();
				httpConn.setRequestProperty(mapKey, mapValue);
			}
			writer = new PrintWriter(httpConn.getOutputStream());
			writer.write(text);
			writer.flush();
			
			int respCode = httpConn.getResponseCode();
			if (respCode == 200) {
				success = "1";
				msg = getStringFromInputStream(httpConn.getInputStream());
			}else{
				success = "2";
				msg = "response_status: " + respCode;
			}
		} catch (Exception e) {
			success = "2";
			//msg = e.getMessage();
		}finally {
			if(httpConn != null)
				httpConn.disconnect();
			close(writer);
		}
		
		
		result.put("msg", msg);
		result.put("success", success);
		return result;
	}
	public static Map<String, String> post(String urlStr, String text) {
		PrintWriter writer = null;
		HttpURLConnection httpConn = null;
		Map<String, String> result = new HashMap<String, String>();
		String msg = "";
		String success = "0";
		
		
		try {// 获取HttpURLConnection连接对象
			URL url = new URL(urlStr);
			httpConn = (HttpURLConnection) url.openConnection();
			// 设置连接属性
			httpConn.setConnectTimeout(20000);
			httpConn.setReadTimeout(30000);
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setUseCaches(false);
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Charset", CHARSET);
			//httpConn.setRequestProperty("Content-Type", "application/json");
			httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			httpConn.setRequestMethod("POST");
			
			writer = new PrintWriter(httpConn.getOutputStream());
			writer.write(text);
			writer.flush();

			int respCode = httpConn.getResponseCode();
			if (respCode == 200) {
				success = "1";
				msg = getStringFromInputStream(httpConn.getInputStream());
			}else{
				success = "2";
				msg = "response_status: " + respCode;
			}
		} catch (Exception e) {
			success = "2";
			//msg = e.getMessage();
		}finally {
			if(httpConn != null)
				httpConn.disconnect();
			close(writer);
		}
		
		
		result.put("msg", msg);
		result.put("success", success);
		return result;
	}

	public static Map<String, String> postJson(String urlStr, String text) {
		PrintWriter writer = null;
		HttpURLConnection httpConn = null;
		Map<String, String> result = new HashMap<String, String>();
		String msg = "";
		String success = "0";


		try {// 获取HttpURLConnection连接对象
			URL url = new URL(urlStr);
			httpConn = (HttpURLConnection) url.openConnection();
			// 设置连接属性
			httpConn.setConnectTimeout(20000);
			httpConn.setReadTimeout(30000);
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setUseCaches(false);
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Charset", CHARSET);
			//httpConn.setRequestProperty("Content-Type", "application/json");
			httpConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			httpConn.setRequestMethod("POST");

			writer = new PrintWriter(httpConn.getOutputStream());
			writer.write(text);
			writer.flush();

			int respCode = httpConn.getResponseCode();
			if (respCode == 200) {
				success = "1";
				msg = getStringFromInputStream(httpConn.getInputStream());
			}else{
				success = "2";
				msg = "response_status: " + respCode;
			}
		} catch (Exception e) {
			success = "2";
			//msg = e.getMessage();
		}finally {
			if(httpConn != null)
				httpConn.disconnect();
			close(writer);
		}


		result.put("msg", msg);
		result.put("success", success);
		return result;
	}
	
	public static Map<String, String> get(String urlStr) {
		PrintWriter writer = null;
		HttpURLConnection httpConn = null;
		Map<String, String> result = new HashMap<String, String>();
		String msg = "";
		String success = "0";
		
		
		try {// 获取HttpURLConnection连接对象
			URL url = new URL(urlStr);
			httpConn = (HttpURLConnection) url.openConnection();
			// 设置连接属性
			httpConn.setConnectTimeout(20000);
			httpConn.setReadTimeout(30000);
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setUseCaches(false);
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Charset", CHARSET);
			httpConn.setRequestProperty("Content-Type", "text/html");
			httpConn.setRequestMethod("GET");
			

			int respCode = httpConn.getResponseCode();
			if (respCode == 200) {
				success = "1";
				msg = getStringFromInputStream(httpConn.getInputStream());
			}else{
				success = "2";
				msg = "response_status: " + respCode;
			}
		} catch (Exception e) {
			success = "2";
			//msg = e.getMessage();
		}finally {
			if(httpConn != null)
				httpConn.disconnect();
			close(writer);
		}
		
		
		result.put("msg", msg);
		result.put("success", success);
		return result;
	}
	
	
	private static final void close(Closeable closeable) {
		if (closeable != null) {
			try {
				closeable.close();
			} catch (IOException e) {
			}
		}
	}
	
	public static String getStringFromInputStream(InputStream inputStream) {
		StringBuffer str = new StringBuffer();
		BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
		try {
			String temp;
			while ((temp = br.readLine()) != null) {
				str.append(temp);
			}
		} catch (IOException e) {
		} finally {
			close(inputStream);
		}
		return str.toString();
	}

	public Map<String, Object> getFile(String src, String dest) {
		LOG.debug("getFile 请求url: " + src + " dest: " + dest);
		PrintWriter writer = null;
		HttpURLConnection httpConn = null;
		Map<String, Object> result = new HashMap<String, Object>();
		String msg = "";
		File destFile = null;
		String success = "0";
		InputStream is = null;
		try {// 获取HttpURLConnection连接对象
			URL url = new URL(src);
			httpConn = (HttpURLConnection) url.openConnection();
			// 设置连接属性
			httpConn.setConnectTimeout(20000);
			httpConn.setReadTimeout(30000);
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setUseCaches(false);
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Charset", "utf-8");
			httpConn.setRequestMethod("GET");
			is = httpConn.getInputStream();
			int respCode = httpConn.getResponseCode();
			if (respCode == 200) {
				success = "1";
				destFile = getFileFromInputStream(is, dest);
			}else{
				success = "2";
				msg = "response_status: " + respCode;
				LOG.debug("get 请求url返回结果失败，code：" + respCode);
			}
		} catch (Exception e) {
			e.printStackTrace();
			success = "3";
			//msg = e.getMessage();
		}finally {
			if(httpConn != null)
				httpConn.disconnect();
			close(writer);
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
		}

		result.put("msg", msg);
		result.put("file", destFile);
		result.put("success", success);
		return result;
	}

	/**
	 * 获取InputStream中的文件
	 */
	public final File getFileFromInputStream(InputStream in, String dest){
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		File destFile = new File(dest);

		try {
			if (!destFile.exists()) {
				// 先得到文件的上级目录，并创建上级目录，在创建文件
				destFile.getParentFile().mkdir();
				destFile.createNewFile();
			}
			bis = new BufferedInputStream(in);
			bos = new BufferedOutputStream(new FileOutputStream(destFile));

			byte[] buf = new byte[1024 * 2];
			int length = bis.read(buf);
			while (length != -1) {
				bos.write(buf, 0, length);
				length = bis.read(buf);
			}
		} catch (IOException e1) {
			LOG.error("IOException ", e1);
		}finally{
			close(bis);
			close(bos);
		}
		return destFile;
	}

	public static void main(String[] args){
//		LOG.debug("kaishi");
//		JSONObject json = new JSONObject();
//		json.put("code","1");
//		json.put("amount","10");
//		json.put("account","157114517051");
//		json.put("payNo","111");
//		Map<String,String> resultMap = postJson("http://localhost:8085/web/itf/dsyyt/rechargeRecord",String.valueOf(json));
//		LOG.debug("kaishi:"+resultMap.get("msg"));
		//getFile("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQGF7zwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyVXp0VTR5a1ZhbmUxcVRVV2h1Y0EAAgSvsXpeAwQIBwAA","E:\\PIC\\123.jpg");
	}
}
